package api

import (
	"bytes"
	"fmt"
	"github.com/gin-gonic/gin"
	"go-caipu/pkg/api/helper"
	"go-caipu/pkg/constant"
	"go-caipu/pkg/services/sqlstore/migrations/util"
	"go-caipu/pkg/services/tools/models"
	"path/filepath"
	"strconv"
	"strings"
	"text/template"
)

// PreviewCode preview预览代码生成
func (hs *HTTPServer) PreviewCode(c *gin.Context) {
	id := c.Param("id")
	sysTable, err := hs.toolService.GetSysTableByTableName(id)
	if err != nil {
		helper.ErrorWithDetail(c, constant.CodeErrInternalServer, constant.ErrTypeInternalServer, err)
		return
	}

	sysTable.ModuleName = strings.Replace(sysTable.ModuleName, "_", "", -1)

	var result = make([]Template, 0)
	files := []string{
		"go-caipu/pkg/api/api.go.tpl",
		"go-caipu/pkg/api/route.go.tpl",
		"go-caipu/pkg/services/package/model.go.tpl",
		"go-caipu/pkg/services/package/dto/model.go.tpl",
		"go-caipu/pkg/services/package/impl/service.go.tpl",
		"go-caipu/pkg/services/package/impl/service_test.go.tpl",
		"go-caipu/pkg/services/package/impl/store.go.tpl",
		"go-caipu/pkg/services/package/impl/store_test.go.tpl",

		"go-caipu-ui/src/apis/package/index.ts.tpl",
		"go-caipu-ui/src/views/package/index.vue.tpl",
		"go-caipu-ui/src/views/package/FormAddModel.vue.tpl",
		"go-caipu-ui/src/views/package/FormDetailDrawer.vue.tpl",
	}
	template := TemplateParseWrite{SysTable: sysTable}
	for _, v := range files {
		tempFile := filepath.Join(util.GetProgramPath(), "resources/template", v)
		path := strings.Replace(v, "package", sysTable.PackageName, -1)
		paths, fileName := filepath.Split(path)
		item := Template{FileName: strings.Replace(fileName, ".tpl", "", -1), Path: paths}
		byte, err := template.Execute(tempFile)
		if err != nil {
			item.Content = fmt.Sprintf("error:%s", err.Error())
		} else {
			item.Content = byte.String()
		}
		result = append(result, item)
	}
	helper.SuccessWithData(c, result)
}

// TemplateParseWrite 模板内容转换
type TemplateParseWrite struct {
	SysTable models.SysTables
}

func (t *TemplateParseWrite) Execute(path string) (bytes.Buffer, error) {
	var b1 bytes.Buffer
	t1, err := template.ParseFiles(path)
	if err != nil {
		return b1, err
	}
	err = t1.Execute(&b1, t.SysTable)
	return b1, err
}

type Template struct {
	FileName string `json:"fileName""`
	Content  string `json:"content"`
	Path     string `json:"path"`
}

// GenCodeHandler 生成代码
func (hs *HTTPServer) GenCodeHandler(c *gin.Context) {
	helper.SuccessWithOutData(c)
}

// GenDBHandler 生成数据库
func (hs *HTTPServer) GenDBHandler(c *gin.Context) {
	id, err := strconv.Atoi(c.Param("id"))
	if err != nil {
		helper.ErrorWithDetail(c, constant.CodeErrInternalServer, constant.ErrTypeInternalServer, err)
		return
	}
	err = hs.toolService.GenToDB(id)
	if err != nil {
		helper.ErrorWithDetail(c, constant.CodeErrInternalServer, constant.ErrTypeInternalServer, err)
		return
	}
	helper.SuccessWithOutData(c)
}
